package com.dayuanit.atm.util;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

public class ExcelUtils {


    public static void processExcel(InputStream is) throws Exception{
        HSSFWorkbook workbook = new HSSFWorkbook(is);

        List<List<Map<String, Object>>> juanList = new ArrayList<>();

        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            HSSFSheet sheet = workbook.getSheetAt(i);
            List<Map<String, Object>> maps = ExcelUtils.proceeSheet(sheet);
            juanList.add(maps);
        }

        for (List<Map<String, Object>> list : juanList) {
            for (Map<String, Object> map : list) {
                System.out.println(map.get("topTitle"));
                List<String> optList = (List<String>)map.get("options");
                for (String opt : optList) {
                    System.out.println(opt);
                }
            }
            System.out.println("-------------------------------");
        }

    }

    private static List<Map<String, Object>> proceeSheet(HSSFSheet sheet) {
        List<Map<String, Object>> topList = new ArrayList<>();

        boolean flag = false;
        for (Row row : sheet) {
            if (!flag) {
                flag = true;
                continue;
            }

            Map<String, Object> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            map.put("options", list);

            topList.add(map);

            final Iterator<Cell> iterator = row.cellIterator();

            while (iterator.hasNext()) {
                Cell cell = iterator.next();
                cell.setCellType(CellType.STRING);

//                System.out.println(cell.getStringCellValue());

                if (!map.containsKey("topTitle")) {
                    map.put("topTitle", cell.getStringCellValue());
                    continue;
                }

                list.add(cell.getStringCellValue());
            }
        }

        return topList;
    }
}
